#include "jtt809_exception.h"

#include <iostream>
#include <string>
#include <boost/stacktrace/stacktrace.hpp>
#include <spdlog/spdlog.h>

using namespace protocol;

const char* JTT809Exception::what() const noexcept
{
	const std::string ch = (std::to_string(static_cast<int>(errCode)) + ":" + message);
	const auto wh = new char[ch.size()+1];
	memcpy(wh, ch.data(), ch.size()+1);
	return wh;
}

JTT809Exception::JTT809Exception(const JTT809ErrorCode errorCode)
{
	errCode = errorCode;
}

JTT809Exception::JTT809Exception(const JTT809ErrorCode errorCode, const std::string& message)
{
	this->errCode = errorCode;
	this->message = message;
}

const std::string& JTT809Exception::stacktrace() noexcept
{
	auto traces = boost::stacktrace::stacktrace().as_vector();
	static auto cause = std::string("Caused by ");
	auto help = std::string("");
	auto it_begin = traces.begin();
	it_begin += 3;
	auto it_end = traces.end();
	it_end -= 6;
	while (it_begin != it_end) {
		cause += (help + to_string(*it_begin) + '\n');
		help = "by ";
		++it_begin;
	}
	return cause;
}
